import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/SignUtil.dart';
import '../../entity/goods_list_entity.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import '../../base/Constant.dart';
import '../goods/GoodsDetail.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../util/AppSaveInfoUtil.dart';

class BrandDetailPage extends StatefulWidget {
  String brand_id;
  BrandDetailPage({Key key, this.brand_id}) : super(key: key);

  @override
  _BrandDetailPageState createState() => _BrandDetailPageState();
}

class NewsTab {
  String text;
  String index;
  String state;
  NewsTab(this.text, this.index, this.state);
}

class _BrandDetailPageState extends State<BrandDetailPage> {
  List<GoodsModelData> shopData = [];
  EasyRefreshController _controller = EasyRefreshController();
  String token = "";
  String logo;
  String introduce;
  String img;
  var _currentIndex = 0;
  int page = 1;
  final List<NewsTab> newsTabs = <NewsTab>[
    new NewsTab('综合', '0', '1'),
    new NewsTab('新品', '1', '0'),
    new NewsTab('销量', '2', '0'),
    new NewsTab('价格', '3', '0'),
  ];
  String is_collect = 'N';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      children: <Widget>[
        Container(
            color: f0Color,
            child: new NotificationListener(
              onNotification: (ScrollNotification note) {
                if (note is ScrollUpdateNotification && note.depth == 0) {}
                return false;
              },
              child: new EasyRefresh(
                  // enableControlFinishRefresh: true,
                  // enableControlFinishLoad: true,
                  controller: _controller,
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  onRefresh: () async {
                    page = 1;
                    getRecommend();
                  },
                  onLoad: () async {
                    page++;
                    getRecommend();
                  },
                  child: CustomScrollView(shrinkWrap: true, slivers: <Widget>[
                    SliverToBoxAdapter(
                        child: Container(
                            child: Stack(children: <Widget>[
                      Positioned(
                        //背景图
                        top: 0,
                        left: 0,
                        child:(img == null || img == '')
                                  ?Image.asset("images/pic_default.png", width: ScreenUtil.getInstance().setWidth(750),)
                                  :
                                   CachedNetworkImage(
                                      width: ScreenUtil.getInstance().setWidth(750),
                                      fit: BoxFit.fill,
                                      imageUrl: Api.BaseUrl +
                                          'public/upload/' +
                                          logo,
                                      placeholder: (context, url) =>
                                          Image.asset(
                                        'images/pic_default.png',
                                        width: ScreenUtil.getInstance().setWidth(750),
                                      ),
                                      errorWidget: (context, url, error) =>
                                          Image.asset(
                                        'images/pic_default.png',
                                        width: ScreenUtil.getInstance().setWidth(750),
                                      ),
                                    ),
                          height: kWindowstateHeight +
                              kSearchBarHeight * 2 +
                              kMargin100 / 2,
                          width: ScreenUtil.getInstance().setWidth(750),
                        // ),
                      ),
                      Container(
                        margin: EdgeInsets.fromLTRB(
                            0,
                            kWindowstateHeight +
                                kSearchBarHeight * 2 +
                                kMargin100 / 2,
                            0,
                            0),
                        width: ScreenUtil.getInstance().setWidth(750),
                        color: Colors.white,
                        child: Column(
                          children: <Widget>[
                            Container(
                                padding: EdgeInsets.fromLTRB(
                                    kMargin20, kMargin20, kMargin20, 0),
                                alignment: Alignment.centerRight,
                                child: GestureDetector(
                                  child: Container(
                                      alignment: Alignment.center,
                                      width: ScreenUtil.getInstance()
                                          .setWidth(140),
                                      height: ScreenUtil.getInstance()
                                              .setWidth(140) *
                                          0.4,
                                      decoration: BoxDecoration(
                                          border: Border.all(color: Colors.red),
                                          // color: Color.fromRGBO(
                                          //     253, 232, 227, 1),
                                          borderRadius: BorderRadius.circular(
                                              ScreenUtil.getInstance()
                                                      .setWidth(140) *
                                                  0.4 /
                                                  2)),
                                      // child: Row(
                                      //   children: <Widget>[
                                        //  is_collect == 'N'
                                        //           ? Icon(Icons.add)
                                        //           : Container(),
                                          // Expanded(
                                          //   // flex: 1,
                                            child: 
                                            is_collect == 'N'
                                                ? Text(
                                                    '关注',
                                                    style: TextStyle(
                                                        color: Colors.black),
                                                  )
                                                : Text(
                                                    '已关注',
                                                    style: TextStyle(
                                                        color: mainColor),
                                                  ),
                                        //   )
                                        // ],
                                      // )
                                      ),
                                  onTap: () {
                                    is_collect == 'Y'
                                        ? cancelCollect()
                                        : collect();
                                  },
                                )),
                            Container(
                              padding: EdgeInsets.fromLTRB(
                                  kMargin20, kMargin20, kMargin20, 0),
                              margin: EdgeInsets.fromLTRB(
                                  0, kMargin10, 0, kMargin20),
                              alignment: Alignment.centerLeft,
                              child: introduce == null
                                  ? Text('品牌介绍')
                                  : Text(introduce),
                            ),
                            Container(
                              height: 1,
                              color: f0Color,
                            ),
                            _buildTab(),
                            Container(
                              height: 10,
                              color: f0Color,
                            ),
                          ],
                        ),
                      ),
                      Positioned(
                        //头像
                        top: kSearchBarHeight * 2 + kMargin15 * 3,
                        left: kMargin15,
                        child: Container(
                            // color: Colors.blue,
                            child: ClipRRect(
                          borderRadius: BorderRadius.circular(kMargin20),
                          child: logo == null || logo == ''
                              ? Image.asset('images/logo.png',
                                  width:
                                      ScreenUtil.getInstance().setWidth(DP_120),
                                  height:
                                      ScreenUtil.getInstance().setWidth(DP_120))
                              : CachedNetworkImage(
                                  width:
                                      ScreenUtil.getInstance().setWidth(DP_120),
                                  height:
                                      ScreenUtil.getInstance().setWidth(DP_120),
                                  fit: BoxFit.fill,
                                  imageUrl: Api.BaseUrl +
                                      'public/upload/' +
                                      logo.replaceAll('\\', '/'),
                                  placeholder: (context, url) => Image.asset(
                                      'images/pic_default.png',
                                      width: ScreenUtil.getInstance()
                                          .setWidth(DP_120),
                                      height: ScreenUtil.getInstance()
                                          .setWidth(DP_120)),
                                  errorWidget:
                                      (context, url, error) =>
                                          Image.asset('images/pic_default.png',
                                              width: ScreenUtil.getInstance()
                                                  .setWidth(DP_120),
                                              height: ScreenUtil.getInstance()
                                                  .setWidth(DP_120)),
                                ),
                        )),
                      ),
                    ]))),
                    SliverGrid(
                      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: ScreenUtil.getInstance().setWidth(750) / 2,
                        mainAxisSpacing: 0,
                        crossAxisSpacing: 0,
                        childAspectRatio: 0.65, //子控件宽高比
                      ),
                      delegate: SliverChildBuilderDelegate(
                        (BuildContext context, int index) {
                          return shopData.length > 0
                              ? getItemContainer(context, index)
                              : Container();
                        },
                        childCount: shopData.length,
                      ),
                    ),
                  ])),
            )),
        Positioned(
            //返回按钮
            top: kSearchBarHeight / 2 + kWindowstateHeight - kMargin10,
            left: kMargin20,
            child: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Container(
                // color: Colors.blue,
                child: Image.asset('images/shangpin_fanhui.png'),
              ),
            )),
      ],
    ));
  }

  _buildTab() {
    return Container(
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      width: ScreenUtil.getInstance().setWidth(750),
      height: tabHeight,
      // alignment: Alignment.center,
      color: Colors.white,
      child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: newsTabs.map((item) {
            return GestureDetector(
              //手势监听控件，用于监听各种手势
              child: Container(
                  width: ScreenUtil.getInstance().setWidth(750) / 4 - 4 * kMargin5,
                  // padding: EdgeInsets.fromLTRB(
                  //     ScreenUtil.getInstance().setSp(27),
                  //     0,
                  //     ScreenUtil.getInstance().setSp(27),
                  //     0),
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border(
                          bottom: item.state == '1'
                              ? BorderSide(width: 2, color: Colors.red)
                              : BorderSide(width: 1, color: white)),
                    ),
                    child: FlatButton(
                      child: Text(item.text,
                          style: item.state == '1'
                              ? TextStyle(
                                  fontWeight: FontWeight.w400,
                                  fontSize: ScreenUtil.getInstance().setSp(25),
                                  color: Colors.red)
                              : TextStyle(fontWeight: FontWeight.w400,
                                  fontSize: ScreenUtil.getInstance().setSp(25),)),
                      onPressed: () {
                        setState(() {
                          _currentIndex = int.parse(item.index);
                          for (var item2 in newsTabs) {
                            item2.state = '0';
                          }
                          newsTabs[int.parse(item.index)].state = '1';
                        });
                      },
                    ),
                  )),
              //onSelectTab函数的使用非常巧妙，
              //相当于定义了一个接口，可操控当前控件以外的数据
            );
          }).toList()),
    );
  }

//商品单个cell
  getItemContainer(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        // TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            // text: shopData[index].zk_final_price,
            text: MONEY + shopData[index].price,
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(28),
                fontWeight: FontWeight.w600)),
        TextSpan(
          // text: shopData[index].reserve_price,
          text: shopData[index].old_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          GoodsModelData model = shopData[index];
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return GoodsDetailPage(
              goods_id: model.goods_id,
              img: model.img,
            );
          }));
        },
        child:  Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(kMargin10)),
                    // color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    padding: EdgeInsets.fromLTRB(kMargin10, 0, kMargin10, 0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        shopData[index].img == '' || shopData[index].img == null
                            ? Image.asset(
                                'images/pic_default.png',
                                width: (ScreenUtil.getInstance().setWidth(750) -
                                        kMargin30) /
                                    2,
                                height:
                                    (ScreenUtil.getInstance().setWidth(750) -
                                            kMargin30) /
                                        2,
                              )
                            : CachedNetworkImage(
                                width: (ScreenUtil.getInstance().setWidth(750) -
                                        kMargin30) /
                                    2,
                                height:
                                    (ScreenUtil.getInstance().setWidth(750) -
                                            kMargin30) /
                                        2,
                                fit: BoxFit.fill,
                                imageUrl: Api.BaseUrl +
                                    'public/upload/' +
                                    shopData[index].img.replaceAll('\\', '/'),
                                placeholder: (context, url) => Image.asset(
                                  'images/pic_default.png',
                                  width:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                  height:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                ),
                                errorWidget: (context, url, error) =>
                                    Image.asset(
                                  'images/pic_default.png',
                                  width:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                  height:
                                      (ScreenUtil.getInstance().setWidth(750) -
                                              kMargin30) /
                                          2,
                                ),
                              ),
                        Container(
                          height: 2,
                        ),
                        Row(
                          children: <Widget>[
                            ClipOval(
                                child: Image.asset(
                              'images/logo.png',
                              width: ScreenUtil.getInstance().setWidth(38),
                              height: ScreenUtil.getInstance().setWidth(38),
                            )),
                            Container(
                              margin: EdgeInsets.only(left:ScreenUtil.getInstance().setWidth(5) ),
                              child: Text('日尚臻选',style: TextStyle(fontSize:ScreenUtil.getInstance().setSp(22),color: Colors.grey ),)
                            )
                          ],
                        ),
                        Container(
                          height: 2,
                        ),
                        Text(
                          shopData[index].goods_name,
                          maxLines: 2,
                          style: TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: ScreenUtil.getInstance().setSp(26)),
                        ),
                        Container(
                          height: 4,
                        ),
                        shopData[index].lable == '' ||
                                shopData[index].lable == 'null'
                            ? Container()
                            : Container(
                                margin: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_8),
                                    0,
                                    ScreenUtil.getInstance().setHeight(DP_8),
                                    0),
                                child: GridView.builder(
                                  shrinkWrap: true,
                                  padding: EdgeInsets.only(top: 0),
                                  physics: new NeverScrollableScrollPhysics(),
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 4,
                                          mainAxisSpacing:
                                              ScreenUtil.getInstance()
                                                  .setHeight(DP_10),
                                          crossAxisSpacing:
                                              ScreenUtil.getInstance()
                                                  .setHeight(DP_10),
                                          childAspectRatio: 2.4),
                                  itemBuilder:
                                      (BuildContext context, int index1) {
                                    List m = shopData[index].lable.split(';');
                                    return Container(
                                      decoration: BoxDecoration(
                                          color:
                                              Color.fromRGBO(253, 232, 227, 1),
                                          borderRadius:
                                              BorderRadius.circular(3)),
                                      alignment: Alignment.center,
                                      padding: EdgeInsets.all(0.8),
                                      child: Text(
                                        m[index1],
                                        style: TextStyle(
                                            color: Colors.red,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(18)),
                                      ),
                                    );
                                  },
                                  itemCount: shopData[index].lable == null
                                      ? 0
                                      : shopData[index].lable.split(';').length,
                                )),
                        Container(
                          height: 3,
                        ),
                        Container(
                          margin: EdgeInsets.all(kMargin5),
                          child: RichText(
                            textAlign: TextAlign.left,
                            text: TextSpan(
                                style: TextStyle(color: Colors.red),
                                children: [
                                  // TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
                                  TextSpan(
                                      // text: shopData[index].zk_final_price,
                                      text: MONEY + shopData[index].price,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(30),
                                          fontWeight: FontWeight.w600)),
                                  TextSpan(
                                    // text: shopData[index].reserve_price,
                                    text: shopData[index].old_price,
                                    style: TextStyle(
                                        fontSize: 12.0,
                                        color: Colors.grey,
                                        decoration: TextDecoration.lineThrough,
                                        decorationColor: Colors.grey),
                                  ),
                                ]),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    )));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getBrand(widget.brand_id);
    getRecommend();
    getString(TOKEN).then((value) {
      token = value;
      if (value == null) {
      } else {
        isCollect();
      }
    });
  }

  isCollect() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BrandCollect_is_collect),
      'token': token,
      'brand_id': widget.brand_id.toString(),
    });
    print(map);
    Response<String> response = await HttpUtil()
        .post(Api.URL_BrandCollect_is_collect, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    if (code == 1 && mounted) {
      setState(() {
        is_collect = userMap['data']['is_collect'];
      });
    }
  }

  collect() async {
    //收藏
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BrandCollect_collect),
      'token': token,
      'brand_id': widget.brand_id.toString(),
    });
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_BrandCollect_collect, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    if (code == 1 && mounted) {
      isCollect();
    }
  }

  cancelCollect() async {
    //取消收藏
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BrandCollect_cancel),
      'token': token,
      'brand_id': widget.brand_id.toString(),
    });
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_BrandCollect_cancel, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    if (code == 1 && mounted) {
      isCollect();
    }
  }

  getBrand(String brand_id) async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BRAND_MSG),
      'brand_id': brand_id,
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BRAND_MSG, data: getSign(map));
    Map userMap = json.decode(response.data);
    print('品牌信息');
    print(userMap);
    int code = userMap['code'];
    if (code == 1 && mounted) {
      setState(() {
        logo = userMap['data']['brandMsg']['logo'];
        introduce = userMap['data']['brandMsg']['introduce'];
        img = userMap['data']['brandMsg']['img'];
      });
    }
  }

  getRecommend() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_GOODS_LIST),
      'brand_id': widget.brand_id.toString(),
      "p": page.toString()
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    print('商品列表');
    print(userMap);
    GoodsModelEntity goodsEntity = new GoodsModelEntity.fromJson(userMap);
    int code = userMap['code'];
    if (code == 1 && mounted) {
      setState(() {
        if (page == 1) {
          shopData.clear();
          _controller.finishRefresh();
          shopData = goodsEntity.data;
        } else {
          _controller.finishRefresh();
          _controller.finishLoad();
          shopData.addAll(goodsEntity.data);
        }
      });
    }
  }
}
